/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.tag;


import java.io.IOException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.jaxson.util.locale.LocaleUtil;

/**
 * Renders a javascript associative array (Map) of 
 * a java resource bundle.  
 * 
 * @author Joe Maisel
 */
public class ResourceBundleTag extends TagSupport
{
	// default bundle name
	private String bundleName = "/WEB-INF/bundles/resources";
	private String var = "rb";

	private ResourceBundle getBundle( Locale locale ) throws IOException
	{
		return LocaleUtil.getBundle( getBundleName(), locale );
	}

	/**
	 * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
	 */
	@Override
	public int doEndTag() throws JspException
	{
		// get the bundle.
		ResourceBundle rb;
		try
		{
			rb = getBundle( pageContext.getRequest().getLocale() );
		}
		catch( IOException e1 )
		{
			e1.printStackTrace();
			throw new JspException( e1 );
		}

		// buffer output
		StringBuffer output = new StringBuffer();

		// create a javascript map in the buffer.
		output.append( "\n\nvar " + var + "=[];\n" );
		Enumeration<String> keys = rb.getKeys();
		while( keys.hasMoreElements() )
		{
			String key = keys.nextElement();
			String value = rb.getString( key );
			output.append( var + "[\"" + key + "\"]=\"" + value + "\";\n" );
		}

		// render
		try
		{
			JspWriter writer = pageContext.getOut();
			writer.println( output );
			writer.flush();
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}

		return super.doEndTag();
	}

	/**
	 * @return the bundleName
	 */
	public String getBundleName()
	{
		return bundleName;
	}

	/**
	 * @param bundleName
	 *            the bundleName to set
	 */
	public void setBundleName( String bundleName )
	{
		this.bundleName = bundleName;
	}

	/**
	 * @return the var
	 */
	public String getVar()
	{
		return var;
	}

	/**
	 * @param var
	 *            the var to set
	 */
	public void setVar( String var )
	{
		this.var = var;
	}

	private static final long serialVersionUID = -7166798314355070967L;
}
